package com.dlc.felear.xiaoensale.helper;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.deviceUtil.Serialhelper;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.entity.BleRssiDevice;

import org.simple.eventbus.EventBus;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;

public class BlueToochHelper3 implements Handler.Callback {
    private final String TAG = "BlueToochHelper";
    private static BlueToochHelper3 instance;
    private static final int SEARCH_RETRY = 1212;
    private static final int SEARCH_TIME_OUT = 1211;
    private Context context;
    private String deviceModel;
    private String deviceType = "";
    private static final String search_ble_fail = "notFoundBlueDevice";
    private Handler handler;
    private BluetoothManager bluetoothManager;
    private HashMap<String, String> blueDevices = new HashMap<>();
    private Session session;
    private boolean isQuery = false;
    private Ble ble;

    private BlueToochHelper3(Context context) {
        log(TAG);
        this.context = context;
        session = Session.getSession();
        initData(context);
    }

    /**
     * 初始化数据
     *
     * @param context
     */
    private void initData(Context context) {
        deviceType = session.getString(Constant.GZDKSJ, "AOSMITH_1745");
        deviceModel = session.getString(Constant.DCFYCGB);
        bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        handler = new Handler(this);
        ble=Ble.getInstance();
        setParamer(deviceType, deviceModel);
    }

    private BleScanCallback<BleRssiDevice> scanCallback = new BleScanCallback<BleRssiDevice>() {
        @Override
        public void onLeScan(final BleRssiDevice result, int rssi, byte[] scanRecord) {
            synchronized (ble.getLocker()) {
                log("onLeScan:"+JsonHelper.toJson(result));
                if (!TextUtils.isEmpty(result.getBleName())) {
                    xianshiMsg("搜索结果:" + result.getBleName());
                }
                if (!TextUtils.isEmpty(result.getBleName()) && result.getBleName().contains(deviceType)) {
                    blueDevices.put(result.getBleName() + "_" + result.getBleAddress(), result.getBleName());
                    EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
                    sendBlueMsg(result.getBleName());
                    ble.stopScan();
                }
            }
        }

    };
    public void loop() {
        //打开蓝牙
//        bluetoothManager.getAdapter().enable();
    }

    public void scanBluetoothDevices(String nama) {
        deviceType = nama;
        startDiscovery();
        bleStartBleScan();
    }

    private void bleStartBleScan(){
        if(ble.isScanning()){
            ble.stopScan();
        }
        ble.startScan(scanCallback);
    }


    private void startDiscovery() {
        EventBus.getDefault().post(true, Constant.SOUSUO_STATUS);
        if (!bluetoothManager.getAdapter().isEnabled()) {
            bluetoothManager.getAdapter().enable();
            xianshiMsg("打开蓝牙");
        }
        if (bluetoothManager.getAdapter().isDiscovering()) {
            log("startDiscovery: 已经在搜索蓝牙");
            xianshiMsg("取消上一次蓝牙搜索");
            bluetoothManager.getAdapter().cancelDiscovery();
        }
        boolean bb = bluetoothManager.getAdapter().startDiscovery();
        xianshiMsg("启动蓝牙搜索，状态：" + bb);
        log("startDiscovery:" + bb);
    }

    public static BlueToochHelper3 getInstance(Context context) {
        if (instance == null) {
            synchronized (BlueToochHelper3.class) {
                if (instance == null) {
                    instance = new BlueToochHelper3(context);
                }
            }
        }
        return instance;
    }

    /**
     * 搜索蓝牙
     */
    public void searchBlueDevice(String deviceType) {
        try {
            log("蓝牙型号:"+deviceType);
            if (isQuery) {
                xianshiMsg("忽略这次蓝牙搜索");
                return;
            }
            isQuery = true;
            log("搜索蓝牙");
            blueDevices.clear();
            xianshiMsg("开始搜索蓝牙,型号:"+deviceType);
            EventBus.getDefault().post(new HashMap<String, BluetoothDevice>(), Constant.RECIEVE_LY);
            scanBluetoothDevices(deviceType);
            handler.removeMessages(SEARCH_RETRY);
            handler.removeMessages(SEARCH_TIME_OUT);
            handler.sendEmptyMessageDelayed(SEARCH_RETRY, 4000);
            handler.sendEmptyMessageDelayed(SEARCH_RETRY, 8000);
            handler.sendEmptyMessageDelayed(SEARCH_TIME_OUT, 10000);
            EventBus.getDefault().post(true, Constant.SOUSUO_STATUS);
        } catch (Exception e) {
            showToast("数据异常:" + e.getMessage());
        }
    }

    private void showToast(String msg) {
        log("showToast:" + msg);
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void log(String msg) {
        Log.e(TAG, msg);
    }

    /**
     * 接受蓝牙信息
     *
     * @param device
     */
    public void onDeviceFounded(BluetoothDevice device) {
        try {
            if (!TextUtils.isEmpty(device.getName())) {
                xianshiMsg("搜索结果:" + device.getName());
            }
            if (!TextUtils.isEmpty(device.getName()) &&
                    !TextUtils.isEmpty(device.getName())
                    && device.getName().contains(deviceType)) {
                log("onDeviceFounded:" + device.getName());
                blueDevices.put(device.getName() + "_" + device.getAddress(), device.getName());
                EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
                sendBlueMsg(device.getName());
            }
        } catch (Exception e) {
            showToast("数据异常 onDeviceFounded:" + e.getMessage());
        }
    }

    private void sendBlueMsg() {
        isQuery = false;
        handler.removeMessages(SEARCH_RETRY);
        handler.removeMessages(SEARCH_TIME_OUT);
        if (!blueDevices.isEmpty()) {
            String tempList = "";
            List<String> list = new ArrayList<>(blueDevices.values());
            for (int i = 0; i < list.size(); i++) {
                if (i != 0 || (i > 0 && i < list.size() - 1)) {
                    tempList += list.get(i) + "@";
                } else {
                    tempList += list.get(i);
                }
            }
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance()
                    .getKzbSerialNo(), tempList.getBytes(StandardCharsets.US_ASCII));
            log("sendBlueMsg tempList:" + tempList);
            EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
            EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
            xianshiMsg("发送蓝牙结果:" + tempList);
        }
    }

    private void sendBlueMsg(String bleName) {
        isQuery = false;
        log("sendBlueMsg:" + JsonHelper.toJson(blueDevices));
        handler.removeMessages(SEARCH_RETRY);
        handler.removeMessages(SEARCH_TIME_OUT);
        DlcSerialPortClient.getInstance().send(Serialhelper.getInstance()
                .getKzbSerialNo(), bleName.getBytes(StandardCharsets.US_ASCII));
        EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
        EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
        xianshiMsg("返回蓝牙名称:" + bleName);
    }


    public void clearData() {
        log("clearData");
        isQuery = false;
        handler.removeMessages(SEARCH_RETRY);
        handler.removeMessages(SEARCH_TIME_OUT);
        bluetoothManager.getAdapter().cancelDiscovery();
        EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
        xianshiMsg("clearData");
    }


    @Override
    public boolean handleMessage(Message msg) {
        try {
            if (SEARCH_TIME_OUT == msg.what) {
                //蓝牙搜索超时
                log("蓝牙搜索超时");
                timeOut();
            } else if (SEARCH_RETRY == msg.what) {
                log("发送蓝牙搜索结果");
                tryAgin();
            }
        } catch (Exception e) {
            showToast("数据异常:" + e.getMessage());
        }
        return false;
    }

    private void timeOut() {
        log("开始发送蓝牙数据");
        isQuery = false;
        ble.stopScan();
        EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
    }

    private void tryAgin() {
//        log("tryAgin:" + JsonHelper.toJson(blueDevices));
        scanBluetoothDevices(deviceType);
    }

    public void setParamer(String name, String type) {
        log("name:" + name + " type:" + type);
        deviceType = name;
        deviceModel = type;
    }

    public void stopScan() {
        bluetoothManager.getAdapter().cancelDiscovery();
    }

    public void sendHandsha() {
        try {
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getKzbSerialNo(),
                    deviceModel.getBytes(StandardCharsets.US_ASCII));
        } catch (Exception e) {
            showToast("数据异常:" + e.getMessage());
        }
    }

    public void clearBluData() {
        isQuery = false;
        blueDevices.clear();
        EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
    }

    private void xianshiMsg(String msg) {
        EventBus.getDefault().post(msg, Constant.SERIALMSG);
    }
}
